package com.example.demo.modules.demo.controller;

import com.example.demo.common.r2dbc.BaseController;
import com.example.demo.modules.demo.dto.FluxDemo;
import com.example.demo.modules.demo.entity.User;
import com.example.demo.modules.demo.services.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import springfox.documentation.annotations.ApiIgnore;

import java.time.Duration;
import java.util.Date;

@RestController
@RequestMapping("/demo")
public class DemoController extends BaseController {

    @Autowired
    private UserService userService;

    @GetMapping("/hello")
    @ApiOperation("测试webflux")
    public Mono<String> hello(ServerWebExchange webExchange){
        return Mono.just("hello world !");
    }

    @GetMapping("/testError")
    @ApiOperation("测试Mono异常")
    public Mono<String> testError(ServerWebExchange webExchange){
        int num = 2 / 1;
        return Mono.just(Integer.toString(num));
    }

    @GetMapping("/r2dbc")
    @ApiOperation("测试r2dbc")
    public Flux<User> r2dbc(ServerWebExchange webExchange){
        return userService.findAll().log(log);
    }

    @GetMapping("/r2dbcTempleate")
    @ApiOperation("测试r2dbcTempleate")
    public Mono<User> r2dbcTempleate(ServerWebExchange webExchange){
        return userService.test().log(log);
    }

    @GetMapping(value = "/stream",produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    @ApiOperation("流式返回测试")
    public Flux<FluxDemo> priceStream(ServerWebExchange webExchange){
        return Flux.interval(Duration.ofSeconds(1))
                .map(l-> new FluxDemo(new Date()))
                .log(log);
    }

    @GetMapping(value = "/streamR2",produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    @ApiOperation("流式返回测试")
    public Flux<User> streamR2(ServerWebExchange webExchange){
        return userService.findAll()
                .skip(1)
                .take(100)
                .delayElements(Duration.ofMillis(5))
                .log(log);
    }
}
